package cn.mooncode.basketballManage.controller;


import cn.mooncode.basketballManage.pojo.Coachinfo;
import cn.mooncode.basketballManage.pojo.RespBean;
import cn.mooncode.basketballManage.pojo.RespPageBean;
import cn.mooncode.basketballManage.pojo.UserCoachinfo;
import cn.mooncode.basketballManage.service.ICoachinfoService;
import cn.mooncode.basketballManage.service.IUserCoachinfoService;
import cn.mooncode.basketballManage.utils.UserUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jwz
 * @since 2021-03-28
 */
@RestController
@RequestMapping("/coachinfo")
public class CoachinfoController {

    @Autowired
    private ICoachinfoService coachinfoService;
    @Autowired
    private IUserCoachinfoService userCoachinfoService;

    @ApiOperation(value = "添加教练信息")
    @PostMapping("/")
    @Transactional
    public RespBean addCouchInfo(@RequestBody Coachinfo coachinfo) {
        if (coachinfoService.save(coachinfo)) {
            Integer cid = coachinfo.getId();
            Integer uid = UserUtils.getUser().getId();
            UserCoachinfo userCoachinfo = new UserCoachinfo();
            userCoachinfo.setUid(uid);
            userCoachinfo.setCid(cid);
            if (userCoachinfoService.save(userCoachinfo)) {
                return RespBean.success("添加成功！");
            }
        }
        return RespBean.error("添加失败！");
    }

    @ApiOperation(value = "查看所有教练信息")
    @GetMapping("/")
    public RespPageBean getAllCoachInfo(@RequestParam(defaultValue = "1") Integer currentPage,
                                        @RequestParam(defaultValue = "2") Integer size, Coachinfo coachinfo) {
        return coachinfoService.getAllCoachInfo(currentPage, size, coachinfo);
    }

    @ApiOperation(value = "获取当前教练信息")
    @GetMapping("/currentCoach")
    public Coachinfo getCurrentCoach() {
        Integer id = UserUtils.getUser().getId();
        return coachinfoService.getCurrentCoach(id);
    }

    @ApiOperation(value = "修改教练信息")
    @PutMapping("/")
    public RespBean updateCoachInfo(@RequestBody Coachinfo coachinfo) {
        if (coachinfoService.updateById(coachinfo)) {
            return RespBean.success("修改成功！");
        } else {
            return RespBean.error("修改失败！");
        }
    }

    @ApiOperation(value = "删除教练信息")
    @DeleteMapping("/{id}")
    @Transactional
    public RespBean deleteCoachInfo(@PathVariable Integer id) {
        if (coachinfoService.removeById(id)) {
            if (userCoachinfoService.remove(new QueryWrapper<UserCoachinfo>().eq("cid", id))) {
                return RespBean.success("删除成功！");
            }
        }
        return RespBean.error("删除失败！");
    }
}
